package com.ifast.car.controller;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.ifast.car.domain.CarInfoDO;
import com.ifast.car.domain.CarPositionDO;
import com.ifast.car.domain.CarPositionDTO;
import com.ifast.car.service.CarInfoService;
import com.ifast.car.service.CarPositionService;
import com.ifast.common.type.EnumErrorCode;
import com.ifast.common.utils.ImportExcelUtil;
import com.ifast.common.utils.Result;
import com.ifast.common.utils.StringUtils;

/**
 * 
 * <pre>
 * 车辆位置信息
 * </pre>
 * 
 * <small> 2018-04-11 17:16:52 | lvyq</small>
 */
@Controller
@RequestMapping("/car/carPosition")
public class CarPositionController {
	@Autowired
	private CarPositionService carPositionService;

	@Autowired
	private CarInfoService carInfoService;

	@GetMapping()
	@RequiresPermissions("car:carPosition:carPosition")
	String CarPosition() {
		return "car/carPosition/carPosition";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("car:carPosition:carPosition")
	public Result<Page<CarPositionDTO>> list(Integer pageNumber, Integer pageSize, CarPositionDTO carPositionDTO) {
		// 查询列表数据
		Page<CarPositionDTO> page = new Page<>(pageNumber, pageSize);
		List<CarPositionDTO> CarPositionList =  carPositionService.getCarPosition(carPositionDTO);
		page.setRecords(CarPositionList);
		page.setTotal(CarPositionList.size());
		return Result.ok(page);
	}

	@GetMapping("/add")
	@RequiresPermissions("car:carPosition:add")
	String add() {
		return "car/carPosition/add";
	}

	@GetMapping("/edit/{positionid}")
	@RequiresPermissions("car:carPosition:edit")
	String edit(@PathVariable("positionid") Long positionid, Model model) {
		CarPositionDO carPosition = carPositionService.selectById(positionid);
		// model.addAttribute("contractTime",
		// DateUtils.format(carPosition.getContractTime(),
		// DateUtils.DATE_TIME_PATTERN_19));
		model.addAttribute("carPosition", carPosition);
		return "car/carPosition/edit";
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("car:carPosition:add")
	public Result<String> save(CarPositionDO carPosition) {
		carPosition.setPositionid(carPositionService.getId()+1);
		if (carPositionService.insert(carPosition)) {
			return Result.ok();
		}
		return Result.fail();
	}

	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("car:carPosition:edit")
	public Result<String> update(CarPositionDO carPosition,String transferMobile) {
		carPosition.setTransferMoblie(transferMobile);
		carPositionService.updateAllColumnById(carPosition);
		return Result.ok();
	}

	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ResponseBody
	@RequiresPermissions("car:carPosition:remove")
	public Result<String> remove(Long positionid) {
		if (carPositionService.deleteById(positionid)) {
			return Result.ok();
		}
		return Result.fail();
	}

	/**
	 * 删除
	 */
	@PostMapping("/batchRemove")
	@ResponseBody
	@RequiresPermissions("car:carPosition:batchRemove")
	public Result<String> remove(@RequestParam("ids[]") Long[] positionids) {
		carPositionService.deleteBatchIds(Arrays.asList(positionids));
		return Result.ok();
	}

	@GetMapping("/batchImport")
	@RequiresPermissions("car:carInfo:batchImport")
	String batchImport() {
		return "car/carPosition/batchImport";
	}

	@ResponseBody
	@PostMapping("/uploadExcel")
	public Result<String> uploadExcel(@RequestParam("file") MultipartFile file) {
		try {
			List<List<Object>> list = new ImportExcelUtil().getBankListByExcel(file.getInputStream(),
					file.getOriginalFilename(), 1);
			for (int i = 0; i < list.size(); i++) {
				
				System.out.println(list.get(i));
				//if (cardao != null) {
					CarPositionDO carPosition = carPositionService.selectById(StringUtils.isNull(list.get(i).size()>=1?list.get(i).get(0) + "":""));
					CarInfoDO cardao = carInfoService.selectById(carPosition.getCid());
					if (carPosition != null&&cardao!=null) {
						//carPosition.setCid(Long.valueOf(StringUtils.isNull(list.get(i).get(1) + "")));
						carPosition.setTransferUsername(StringUtils.isNull(list.get(i).size()>=2?list.get(i).get(1) + "":""));
						carPosition.setTransferMoblie(StringUtils.isNull(list.get(i).size()>=3?list.get(i).get(2) + "":""));
						String[] positions = (StringUtils.isNull(list.get(i).size()>=4?list.get(i).get(3) + "":"").split("\\/"));
						System.out.println(">=>>>>>>>>>>>>"+positions.length);
						JSONArray jas = new JSONArray();
						/*if(carPosition.getNewPosition()!=null&&!"".equals(carPosition.getNewPosition())) {
							jas=JSONArray.parseArray(carPosition.getNewPosition());
						}*/
						for (int j = 0; j < positions.length; j++) {
							JSONObject job = new JSONObject();
							if (jas.size() == 0) {
								job.put("time", cardao.getContractTime());
							}else {
								Calendar calendar = Calendar.getInstance();
								Date date = jas.getJSONObject(jas.size()-1).getDate("time");
								calendar.setTime(date);
						        calendar.add(Calendar.DATE, 1);
						        date = calendar.getTime();
						        job.put("time", date);
							}
							job.put("data", positions[j]);
							jas.add(job);
						}
						carPosition.setNewPosition(JSON.toJSONStringWithDateFormat(jas, "yyyy-MM-dd",
								SerializerFeature.WriteDateUseDateFormat));
						carPositionService.updateById(carPosition);
					}
					
					/*else {
						carPosition = new CarPositionDO();
						carPosition.setPositionid(Long.valueOf(list.get(i).get(0) + ""));
						//carPosition.setCid(Long.valueOf(StringUtils.isNull(list.get(i).get(1) + "")));
						carPosition.setTransferUsername(StringUtils.isNull(list.get(i).get(1) + ""));
						carPosition.setTransferMoblie(StringUtils.isNull(list.get(i).get(2) + ""));
						String[] positions = (StringUtils.isNull(list.get(i).get(3) + "")).split("//");
						JSONArray jas = new JSONArray();
						if(carPosition.getNewPosition()!=null&&!"".equals(carPosition.getNewPosition())) {
							jas=JSONArray.parseArray(carPosition.getNewPosition());
						}
						for (int j = 0; j < positions.length; j++) {
							JSONObject job = new JSONObject();
							if (jas.size() == 0) {
								job.put("time", cardao.getContractTime());
							}else {
								Calendar calendar = Calendar.getInstance();
								Date date = jas.getJSONObject(jas.size()-1).getDate("time");
								calendar.setTime(date);
						        calendar.add(Calendar.DATE, 1);
						        date = calendar.getTime();
						        job.put("time", date);
							}
							job.put("data", positions[j]);
							jas.add(job);
						}
						carPosition.setNewPosition(JSON.toJSONStringWithDateFormat(jas, "yyyy-MM-dd",
								SerializerFeature.WriteDateUseDateFormat));
					}*/

				}
			//}
		} catch (Exception e) {
			e.printStackTrace();
			return Result.build(EnumErrorCode.FileUploadGetBytesError.getCode(),
					EnumErrorCode.FileUploadGetBytesError.getMsg());
		}
		return Result.ok();
	}

	@ResponseBody
	@GetMapping("/api/v1/getPosition") 
	public Result<List<Map<String,Object>>> getPosition(String mobile) {
		List<Map<String,Object>> carPosition = carPositionService.getCarPositionByMobile(mobile);
		if (carPosition != null) {
			return Result.ok(carPosition);
		}
		return Result.ok();
	}
	
	@ResponseBody
	@GetMapping("/api/v1/getPosition2") 
	public JSONPObject getPosition(String jsonpCallback,String mobile) {
		List<Map<String,Object>> carPosition = carPositionService.getCarPositionByMobile(mobile);
		if (carPosition != null) {
			return new JSONPObject(jsonpCallback, Result.ok(carPosition));
		}
		return new JSONPObject(jsonpCallback, Result.ok());
	}

}
